/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Example client for building MaCI Clients apps. (With SQL interface)
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: SQLClientExample.cpp,v 1.8 2009-08-11 08:15:36 amaula Exp $
 *
 */
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <signal.h>
#include <string>
#include <map>
#include "owndebug.h"
#include "ownutils.h"
#include "binbag.h"
#include "SQLClient.hpp"

//*****************************************************************************
// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
// Set initial verbosity level to 1
static int verbose = 1;
//*****************************************************************************
// Choose your namespace
using namespace MaCI;
using namespace MaCI::SQL;
//*****************************************************************************
// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************
static std::string datasource;
static std::string datasourceMaCISL;
//*****************************************************************************
static std::map<unsigned int, std::string> sentQueryMap;
//*****************************************************************************
static unsigned int hammer_interval = 100;
static bool interactive_mode = true;
static unsigned int querytimeout_ms = 30000;
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tSQLClientExample [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-s name]\t\t\tSpecify the data source\n");
  fprintf(stderr,"  \t\t\t\tOR\n");
  fprintf(stderr,"  [-S name]\t\t\tSpecify the data source by MaCISL\n");
  fprintf(stderr,"  [-I]\t\t\t\tDisable interactive mode (Don't)\n");
  fprintf(stderr,"  [-t timems]\t\tSQL query timeout in milliseconds (default 30sec)\n\n");

  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int dummyWatch(CSQLClient *dc)
{
  CSQLData dd;
  CSQLResult sqldata;
  while(run) {
    if (sentQueryMap.size()) {
      dPrint(ODTEST,"SentMap not empty (Got %u entries). Executing.", sentQueryMap.size());
      for(EACH_IN_i(sentQueryMap)) {
        dPrint(ODTEST,"Waiting for reply on queryID %u", i->first);
        if (dc->GetQueryResult(sqldata,i->first, 0)) {
          if (sqldata.GotTable()) {
            dPrint(ODSTATUS,
                   "Got reply for request %u (%s), contains:\n"
                   "******************************************************************************\n"
                   "%s\n"
                   "******************************************************************************",
                   i->first, 
                   i->second.c_str(), 
                   sqldata.GetXMLData().c_str());

          } else if (sqldata.GotError()) {
            dPrint(ODSTATUS,"Request %u (%s) resulted in error: '%s'",
                   i->first, i->second.c_str(),
                   sqldata.GetLastError().c_str());

          }
            sentQueryMap.erase(i);
          break;
        }
        
      }
    }
    ownSleep_ms(hammer_interval >> 1);
  }
  
  return 0;
}
//*****************************************************************************

static int ExecuteExampleClient(gimi::GIMI &g)
{
  char *query;
  // SQL client instance
  // Traditional form, where the GIMI is given as preconnected pointer
  // to the SQLClient instance.
  CSQLClient dc(&g, 0);

  // SQL data instance
  CSQLData dd;
  dd.CreateInternalBinBag();

  // Variable for storing thread id.
  ownThreadHandle dummyWatchThread;

  // Init random generator.
  srandom(time(NULL));

  // Assign default target.
  if (datasource.size()) {
    dc.SetDefaultTarget(datasource);

  } else {
    // GIMI is Open(), so we can execute this.
    MaCICtrl::SMaCISL sl(datasourceMaCISL);
    if (sl.IsValidFQMaCISL()) {
      dc.SetDefaultTarget(sl, 10000);
    }
    
  }
  
  // Open.
  if (dc.Open() == KMaCIOK) {
    dPrint(ODINFO,"Succesfully Open():ed SQLClient, BWT, you have connected to service: '%s'",
           dc.GetDefaultTargetMaCISL().ToMaCISLString().c_str());
    if (interactive_mode) {
      dPrint(ODSTATUS,"Entering interactive mode.\n\n");
      while(run) {
        query = readline("Query: ");
        if (query) {
          CSQLResult qresult;
          const std::string querystr = query;
          free(query);
          if (querystr == "quit") exit(0);
          if (dc.ExecuteQuery(qresult, querystr, querytimeout_ms)) {
            
            switch(qresult.GetResultType()) {
            case KTable: {
              const CSQLTable &t = qresult.GetTable();
              std::vector<unsigned int> columnWidths(t.GetColumnCount());
              
              // Learn column widths
              for(unsigned int j=0; j < t.GetColumnCount(); ++j) {
                // Set width to zero initially.
                columnWidths[j] = 0;
                for(unsigned int i=0; i < t.GetRowCount(); ++i) {
                  const unsigned int size = t.GetField(i,j).GetValueString().size();
                  if (size > columnWidths[j]) columnWidths[j] = size;
                }              
              }
              
              // Print :)
              for(unsigned int i=0; i < t.GetRowCount(); ++i) {
                printf("||   ");
                for(unsigned int j=0; j < t.GetColumnCount(); ++j) {
                  printf("%*s   ||", columnWidths[j]+3, t.GetField(i,j).GetValueString().c_str());
                }
                printf("\n");
              }
              break;
            }
              
            case KError: {
              printf("SQL Error: '%s'\n", qresult.GetLastError().c_str());
              break;
            }
              
            case KAffectedRows:
              printf("Query affected %lld rows.\n", qresult.GetAffectedRows());
              break;
              
            default:
              printf("\nINTERNAL ERROR: SQLResult in unknown state!!!\n");
              break;
            }
            
          }
        }
        
      }
      
    } else {
      dummyWatchThread = ownThread_Create((void*)dummyWatch, &dc);
      
      std::string myquery("select * from userdb");
      bool er;
      
      while(run) {
        unsigned int queryid = 0;
        er = dc.SendQuery(myquery, queryid);
        assert(er == true);
        
        dPrint(ODTEST,"Storing the query to map in place %u", queryid);
        sentQueryMap[queryid] = myquery;
        
        // Wait for a "moment".
        ownSleep_ms(hammer_interval);
      }
    }

  } else {
    dPrint(1,"Failed to Open() SQLClient.");

  }


  return 0;
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 40002;
  std::string gimnetName;

  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(4);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.8 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "t:In:u:p:s:S:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////
    case 't':
      querytimeout_ms = atoi(optarg);
      dPrint(3,"Query timeout set to %ums", querytimeout_ms);
      break;

    case 'I':
      interactive_mode ^= true;
      dPrint(3,"Interactive mode now %s.", interactive_mode?"Enabled":"Disabled");
      break;

    case 's':
      datasource = optarg;
      dPrint(3,"Using DataSource '%s'", optarg);
      break;

    case 'S':
      datasourceMaCISL = optarg;
      dPrint(3,"Using DataSource MaCISL '%s'", optarg);
      break;

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteExampleClient(g);
  }

  return 0;
}
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
 * 
 * $Log: not supported by cvs2svn $
 * Revision 1.7  2009-08-06 11:24:55  amaula
 * Added support for user-specified timeout.
 *
 * Revision 1.6  2009-08-06 09:10:25  amaula
 * Added support for interactive SQL client
 *
 * Revision 1.5  2009-08-06 07:36:22  amaula
 * Error reporting works now.
 *
 * Revision 1.4  2009-08-05 06:09:00  amaula
 * SQL interface structure altered a bit
 *
 * Revision 1.3  2009-08-03 11:00:16  amaula
 * Added internal parameter for test interval
 *
 * Revision 1.2  2009-07-31 12:25:36  amaula
 * Some changes towards working SQL solution :)
 *
 * Revision 1.1  2009-07-31 07:51:58  amaula
 * Initial working SQL interface version
 *
 *****************************************************************************/
//*****************************************************************************
//*****************************************************************************


